package com.chushouya.common.alipay;

import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Jsons;
import com.general.framework.core.lang.Strings;
import com.general.framework.data.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 阿里预授权工具类
 */
@Slf4j
@Component
public class AlipayApiUtil {

    @Resource
    private RedisCache redisCache;

    /**
     * 解析支付宝请求中的参数为Map
     */
    public Map<String, String> request2Map(HttpServletRequest request) {
        Map<String, String[]> requestParam = request.getParameterMap();
        try {
            Map<String, String> paramMap = new HashMap<>();
            for (Map.Entry<String, String[]> entry : requestParam.entrySet()) {
                paramMap.put(entry.getKey(), String.join(",", entry.getValue()));
            }
            log.info("===>支付宝通知参数{}:{}", paramMap.get("notify_type"), Jsons.toJsonString(paramMap));
            return paramMap;
        } catch (Exception e) {
            log.error("解析支付宝回调参数失败:{}", Jsons.toJsonString(requestParam), e);
            throw Ex.systemError("解析支付宝回调参数失败");
        }
    }

    public BigDecimal getBigDecimal(final Map<String, String> notifyMap, final String key) {
        final String value = notifyMap.get(key);
        if (Strings.isNotEmpty(value)) {
            return new BigDecimal(value);
        }
        return null;
    }

    /**
     * 构建身份信息HASH
     *
     * @param realName 真实姓名
     * @param idCardNo 身份证号码
     * @return 身份信息HASH
     */
    private String genIdentityHash(String realName, String idCardNo) {
        try {
            return DigestUtils.sha256Hex(realName + idCardNo);
        } catch (Exception e) {
            log.error("构建身份信息HASH异常", e);
            throw Ex.systemError("构建身份信息HASH异常");
        }
    }

    /**
     * 将字节数组转为十六进制字符串
     */
    private static String convertByteToHexString(byte[] bytes) {
        return Hex.encodeHexString(bytes);
    }


}
